<template>
  <div class="login">
    <div class="logo">
      <img class="img2"
           src="../../assets/img/chengdelogo2.png"
           alt="">
    </div>
    <div class="btn">
      <van-form validate-first
                ref="loginForm"
                @failed="onFailed">
        <!-- 通过 pattern 进行正则校验 -->
        <van-field v-model="account"
                   name="validator1"
                   label="账号："
                   placeholder="请输入账号"
                   :rules="accountRules" />
        <!-- 通过 validator 进行函数校验 -->
        <van-field v-model="password"
                   label="密码："
                   name="validator2"
                   :right-icon="passwordStatus?'eye':'closed-eye'"
                   placeholder="请输入密码"
                   :rules="passwordRules"
                   :type="!passwordStatus?'password':'text'"
                   @click-right-icon="passwordStatus=!passwordStatus" />
        <!-- 通过 validator 进行异步函数校验 -->
        <!-- <van-field v-model="value3"
                   name="asyncValidator"
                   placeholder="异步函数校验"
                   :rules="[{ validator: asyncValidator, message: '请输入正确内容' }]" /> -->
        <div class="button">
          <!-- 按钮 -->
          <van-button round
                      block
                      type="info"
                      native-type="submit"
                      class="info"
                      @click="loginBtn">登录</van-button>
          <van-button round
                      block
                      type="info"
                      class="info2"
                      @click="resetform">重置</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'login',
  components: {},
  mounted() {
    this.initForm() // 初始化表单
  },
  data() {
    return {
      account: '', // 账号
      password: '', // 密码
      passwordStatus: false, // 密码显示/隐藏
      // 账单验证
      accountRules: [
        {
          required: true, // 是否必填
          trigger: 'onBlur'
        },
        {
          // 自定义表单校验
          validator: value => {
            // true:验证通过
            // false:验证不通过
            return value.length != 0
          }
        }
      ],
      // 密码验证
      passwordRules: [
        {
          required: true, // 是否必填
          trigger: 'onBlur'
        },
        {
          // 自定义表单校验
          validator: value => {
            // true:验证通过
            // false:验证不通过
            return value.length != 0
          }
        }
      ]
    }
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    // validator1(val) {
    //   // 校验账号
    //   return /\d{5}/.test(val)
    // },
    // validator2(val) {
    //   // 校验密码
    //   return /\d{6}/.test(val)
    // },
    onFailed(errorInfo) {
      console.log('failed', errorInfo)
    },
    // 初始化表单
    initForm() {
      this.account = this.$cookies.get('privateInfo')?.account || ''
      this.password = this.$cookies.get('privateInfo')?.password || ''
    },
    // 登录
    loginBtn() {
      // 局部表单验证
      this.$refs.loginForm
        .validate()
        .then(() => {
          //  登录请求
          this.requestData()
        })
        .catch(() => {
          this.$Notify({ type: 'danger', message: '登录失败' })
          return false
        })
    },
    // 请求数据
    requestData() {
      console.log('开始请求数据')
      // 发送请求,用GET方式
      let url = '/api/Login/UserInfo'
      // 请求参数
      let data = {
        UserNo: this.account,
        Password: this.password
      }
      this.$axios({
        method: 'GET',
        url: url,
        params: data
      })
        .then(res => {
          // 判断用户是否存在
          if (res.Code !== 2004) {
            // 登录失败
            this.$Notify({ type: 'danger', message: res.Message })
            return
          }
          // 0 登录成功
          this.$Notify({ type: 'success', message: res.Message })
          // 1 获取User信息
          const UserInfo = res.Data
          // 2 存取password
          const privateInfo = {
            account: this.account,
            password: this.password
          }
          // 3 组成完整对象
          const totalInfo = { UserInfo }
          // 4 存入cookie
          this.$cookies.set('totalInfo', totalInfo, '7d', '/')
          this.$cookies.set('privateInfo', privateInfo, '7d', '/')
          // 5 token存入store
          this.$store.commit('updateToken', UserInfo.Token)
          // console.log('拿取一下coookie：', this.$cookies.get('totalInfo'))
          // 5 跳转
          this.$router.push('/index')
        })
        .catch(err => {
          this.$Notify({ type: 'danger', message: '登录失败' })
          console.log('登陆失败')
        })
    },
    // 重置表单
    resetform() {
      this.account = ''
      this.password = ''
    }
  }
}
</script>

<style lang="less">
@import './login.less';
</style>